import { searchConfig, searchList } from "./search";
import { drawerConfig, drawerVisible } from "./drawer";
import { modalConfig, modalVisible } from "./modal";
import { tableData, tableConfig, tableLoading, tablePage } from "./table";
import {
  tableActiveKey,
  drawerFormState,
  tabPower,
  defaultModalVisible,
  defaultModalFormState,
  defaultSearchList,
  defaultDrawerInputValidator,
  set_formState,
  isShowIMH5,
  drawerActiveKey,
} from "./store";
import { fetchSearchMap, fetchDataById } from "./utils";
import { isHasPower } from "@/assets/directives/tools";
import get_selectLabel_modalConfig from "./components/ModalComponent/SelectLabel";
import get_publishDynamic_modalConfig from "./components/ModalComponent/PublishDynamic";
import get_customPosition_modalConfig from "./components/ModalComponent/CustomPosition";
import get_customDistribute_modalConfig from "./components/ModalComponent/CustomDistribute";
import get_activateMember_modalConfig from "./components/ModalComponent/ActivateMember";
import { AxiosResponse } from "axios";
const queryParams = reactive<any>({});
export let tmp_proxy: any = null;
const defineApiMap = new Map([
  [0, () => userApi.queryUserList(queryParams)],
  [1, () => userApi.queryRecordList(queryParams)],
]);
const handleApiTask = async (number) => {
  let api = defineApiMap.get(number) as () => Promise<AxiosResponse<any, any>>;
  const result: any = await api();
  if (result.code != 200) return message.error(result.message);
  tableData.value = result?.data?.list ?? [];
  tablePage.total = result?.data?.attributes?.total ?? 0;
};
export const fetchList = async () => {
  try {
    tableData.value.length = 0;
    tableLoading.value = true;
    queryParams.page = tablePage.current;
    queryParams.page_size = tablePage.pageSize;
    await handleApiTask(tableActiveKey.value);
  } catch (error: any) {
    message.error(error.message);
  } finally {
    tableLoading.value = false;
  }
};
export const refreshTable = async (searchParams: any = {}) => {
  tablePage.current = 1;
  initObjAttr(queryParams, searchParams);
  await fetchList();
};
export const showDrawer = () => (drawerVisible.value = true);
export const showModal = () => (modalVisible.value = true);
export const handleAction = async ({ record, type }: any) => {
  try {
    initObjAttr(defaultDrawerInputValidator[0], createArray(false, 2));
    initObjAttr(defaultDrawerInputValidator[1], createArray(false, 4));
    isShowIMH5.value = true;
    drawerActiveKey.value = 0;
    set_formState(type, drawerFormState, record);
  } catch (error: any) {
    message.error(error.message);
  }
};
export const handleDisabledCustomer = (record: any = {}) => {
  tmp_proxy.$confirm({
    icon: null,
    title: () => <>{$t("base.userStatusEdit")}</>,
    closable: true,
    maskClosable: true,
    style: {
      top: "30%",
    },
    content: (
      <>
        {record.is_lock === 0
          ? !isEmptyType(record.nickname)
            ? `${$t("user2")}"${record.nickname}"${$t("user0")}`
            : `${$t("user3")}"${record.uid}"${$t("user0")}`
          : !isEmptyType(record.nickname)
          ? `${$t("user2")}"${record.nickname}"${$t("user1")}`
          : `${$t("user3")}"${record.uid}"${$t("user1")}`}
      </>
    ),
    onOk: async () => {
      await userApi.updateStatus({
        userId: record.uid,
      });
      message.success($t("base.updateSucess"));
      fetchDataById({ uid: record.uid });
      fetchList();
    },
  });
};
export const handleOpenVip = () => {
  defaultModalVisible[4].value = true;
  defaultModalFormState[4].userId = drawerFormState.uid;
};
export default defineComponent({
  setup(props, { attrs, emit, expose, slots }) {
    const { proxy } = reactive<any>(getCurrentInstance());
    tmp_proxy = proxy;
    const defineSelectLabelModal: any = get_selectLabel_modalConfig();
    const definePublishDynamicModal = get_publishDynamic_modalConfig();
    const defineCustomPositionModal = get_customPosition_modalConfig();
    const defineCustomDistributeModal = get_customDistribute_modalConfig();
    const defineActivateMemberModalConfig = get_activateMember_modalConfig();
    tabPower[0] = isHasPower("userApi.queryUserList");
    tabPower[1] = isHasPower("userApi.queryRecordList");
    tableActiveKey.value = tabPower[0] ? 0 : tabPower[1] ? 1 : Infinity;
    searchList.value = defaultSearchList[tableActiveKey.value] ?? [];
    const defineSearch = searchConfig();
    const defineDrawer = drawerConfig();
    const defineModal = modalConfig();
    const defineTable = tableConfig();
    watch(
      () => sysZone.value,
      () => fetchList()
    );
    onActivated(() => {
      if (tableActiveKey.value === 0) fetchSearchMap();
      fetchList();
    });
    const renderModal = () => (
      <>
        {defaultModalVisible[0].value ? (
          <s-modal {...defineSelectLabelModal} />
        ) : null}
        {defaultModalVisible[1].value ? (
          <s-modal {...definePublishDynamicModal} />
        ) : null}
        {defaultModalVisible[2].value ? (
          <s-modal {...defineCustomPositionModal} />
        ) : null}
        {defaultModalVisible[3].value ? (
          <s-modal {...defineCustomDistributeModal} />
        ) : null}
        {defaultModalVisible[4].value ? (
          <s-modal {...defineActivateMemberModalConfig} />
        ) : null}
      </>
    );
    return () => (
      <>
        {renderModal()}
        <s-design
          defineSearch={defineSearch}
          defineTable={defineTable}
          defineDrawer={defineDrawer}
          defineModal={defineModal}
        />
      </>
    );
  },
});
